package com.bigshen.algorithm.gTree.solution04PostorderTraversal;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {

        List<Integer> list = new ArrayList<>();

        if (null == root) {
            return list;
        }

        // 递归
        //postorder(root, list);

        // Stack
        Stack<TreeNode> stack = new Stack();
        TreeNode node = root;
        TreeNode prev = null;
        while (null != node || !stack.isEmpty()) {
            while (null != node) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            if (null == node.right || prev == node.right) {
                list.add(node.val);
                prev = node;
                node = null;
            } else {
                // 判断有没有right，有right的话重新入队
                stack.push(node);
                node = node.right;
            }
        }

        return list;
    }

    private void postorder(TreeNode node, List<Integer> list) {

        if (null == node) {
            return;
        }

        postorder(node.left, list);
        postorder(node.right, list);
        list.add(node.val);

    }


}
